package cn.innosmart.aq.util;

import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.JsonObjectRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import cn.innosmart.aq.R;
import cn.innosmart.aq.application.AQApplication;
import cn.innosmart.aq.customize.MyDialog;
import cn.innosmart.aq.customize.RoundProgressBar;

public class UpdateManager {
    private static final int DOWN_UPDATE = 1;
    private static final int DOWN_OVER = 2;
    private static final int INTERRUPT = 3;
    private static final int NOTIFY_ID = 0;
    //Context
    private Context mContext;
    // update info
    private String updateMsg;
    // net Path Of apk  http://54.251.116.21/download_aq_01_app_andorid/
    private String apkUrl = "http://www.innosmart.cn/aq_app_info/Download/APP_Android/AQ.apk";
    private Dialog noticeDialog;// dialog notify update
    private Dialog downloadDialog;// download dialog
    private String savePath;// save path to save apk
    private String mFileDir = "AdoreGeek";
    private String saveFileName;
    //
    private RoundProgressBar mProgress;
    private int progress;//
    private Thread downLoadThread; //
    private boolean interceptFlag = false;//
    private String updateurl = "http://www.innosmart.cn/aq_app_info/Download/APP_Android/apk_version.json";
    private JsonObjectRequest jsonObjectRequest;
    private MyDialog myDialog;
    private Button bt_positive;
    private Button bt_negative;
    private Button bt_cancel;
    private TextView tv_content;
    private RelativeLayout rl_cancel;
    private Class<?> cls;
    private NotificationManager mNotificationManager;
    private Notification mNotification;
    private Handler mHandler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWN_UPDATE:
                    //下载开始
                    if (progress < 100) {
                        mProgress.setProgress(progress);
                        RemoteViews contentview = mNotification.contentView;
                        contentview.setTextViewText(R.id.tv_progress, progress + "%");
                        contentview.setProgressBar(R.id.progressbar, 100, progress, false);
                        mNotificationManager.notify(NOTIFY_ID, mNotification);
                    }
                    break;
                case DOWN_OVER:
                    //下载结束
                    myDialog.dismiss();
                    RemoteViews contentview = mNotification.contentView;
                    contentview.setTextViewText(R.id.tv_progress, mContext.getString(R.string.notification_click_info_1));
                    contentview.setTextViewText(R.id.name, mContext.getString(R.string.notification_click_info_2));
                    contentview.setProgressBar(R.id.progressbar, 100, 100, false);
                    mNotification.flags = Notification.FLAG_AUTO_CANCEL;
                    mNotificationManager.notify(NOTIFY_ID, mNotification);
                    installApk();
                    break;
                case INTERRUPT:
                    //暂停
                    mNotificationManager.cancel(NOTIFY_ID);
                    break;
            }
            super.handleMessage(msg);
        }
    };
    private String STATUS_BAR_COVER_CLICK_ACTION = "CANCEL_DOWNLOAD";
    BroadcastReceiver onClickReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(STATUS_BAR_COVER_CLICK_ACTION)) {
                //在这里处理点击事件
                cancelDownloading();
            }
        }
    };
    private int lastRate;
    private Runnable mdownApkRunnable = new Runnable() {
        @Override
        public void run() {
            URL url;
            try {
                interceptFlag = false;
                lastRate = 0;
                url = new URL(apkUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.connect();
                int length = conn.getContentLength();
                InputStream ins = conn.getInputStream();
                System.out.println("savePath=" + savePath);
                File file = new File(savePath);
                if (!file.exists()) {
                    file.mkdir();
                }
                String apkFile = saveFileName;
                System.out.println("saveFileName=" + saveFileName);
                File ApkFile = new File(apkFile);
                FileOutputStream outStream = new FileOutputStream(ApkFile);
                int count = 0;
                byte buf[] = new byte[1024];
                do {
                    int numread = ins.read(buf);
                    count += numread;
                    progress = (int) (((float) count / length) * 100);

                    if (progress > lastRate + 1) {
                        lastRate = progress;
                        mHandler.sendEmptyMessage(DOWN_UPDATE);
                    }
                    if (numread <= 0) {
                        mHandler.sendEmptyMessage(DOWN_OVER);
                        break;
                    }
                    outStream.write(buf, 0, numread);
                } while (!interceptFlag);
                outStream.close();
                ins.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    public UpdateManager(Context context) {
        this.mContext = context;
        savePath = getSDPath() + File.separator + mFileDir + File.separator;
        saveFileName = savePath + "AQ.apk";
    }

    /**
     * 软件更新走市场
     *
     * @param type
     */
    public void geUpdateInfo(final int type) {
//        jsonObjectRequest = new JsonObjectRequest(updateurl, null,
//                new Response.Listener<JSONObject>() {
//                    @Override
//                    public void onResponse(JSONObject response) {
//                        Log.d("TAG", response.toString());
//                        deal(type, response);
//                    }
//                },
//                new Response.ErrorListener() {
//                    @Override
//                    public void onErrorResponse(VolleyError error) {
//                        Log.e("TAG", error.getMessage(), error);
//                    }
//                });
//        AQApplication.getInstance().mQueue.add(jsonObjectRequest);
    }

    private void deal(int type, JSONObject response) {
        try {
            String verName = response.getString("verName");
            String forceupdate = response.getString("forceupdate");
            int verCode = response.getInt("verCode");
            int localVerCode = AQApplication.getInstance().getVersionCode();
            if (localVerCode < verCode) {
                alert();
            } else {
                if (type == 2)
                    Toast.makeText(mContext, mContext.getString(R.string.this_is_newest_app_version), Toast.LENGTH_SHORT).show();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 警告对话框
     */
    private void alert() {
        myDialog = new MyDialog(mContext);
        myDialog.setCanceledOnTouchOutside(false);
        mProgress = (RoundProgressBar) myDialog.findViewById(R.id.rd_pb);
        bt_positive = (Button) myDialog.findViewById(R.id.bt_positive);
        bt_positive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                download();
            }
        });
        bt_negative = (Button) myDialog.findViewById(R.id.bt_negative);
        bt_negative.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myDialog.dismiss();
            }
        });
        myDialog.show();
    }

    /**
     * 下载
     */
    private void download() {
        showDownloadDialog();
        showNotification();
        downloadApk();
    }

    /**
     * 显示下载对话框
     */
    private void showDownloadDialog() {
        rl_cancel = (RelativeLayout) myDialog.findViewById(R.id.rl_cancel);
        bt_cancel = (Button) myDialog.findViewById(R.id.bt_canceldownload);
        tv_content = (TextView) myDialog.findViewById(R.id.tv_content);
        tv_content.setVisibility(View.GONE);
        mProgress.setVisibility(View.VISIBLE);
        bt_negative.setVisibility(View.GONE);
        bt_positive.setVisibility(View.GONE);
        rl_cancel.setVisibility(View.VISIBLE);
        bt_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cancelDownloading();
            }
        });
    }

    private void cancelDownloading() {
        interceptFlag = true;
        mHandler.sendEmptyMessage(INTERRUPT);
        myDialog.dismiss();
        mContext.unregisterReceiver(onClickReceiver);
    }

    /**
     * 显示通知栏下载进度
     */
    private void showNotification() {
        mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext);
        RemoteViews mRemoteViews = new RemoteViews(mContext.getPackageName(), R.layout.notification_updateprogress);
        int icon = R.drawable.push;
        //如果版本号低于（3。0），那么不显示按钮  此处写死，请自行添加3.0版本判断
        if (false) {
            mRemoteViews.setViewVisibility(R.id.notify_cancel, View.GONE);
        } else {
            mRemoteViews.setViewVisibility(R.id.notify_cancel, View.VISIBLE);
        }
        mBuilder.setContent(mRemoteViews)
                .setWhen(System.currentTimeMillis())// 通知产生的时间，会在通知信息里显示
                .setPriority(Notification.PRIORITY_DEFAULT)// 设置该通知优先级
                .setOngoing(true)
                .setSmallIcon(icon);
        IntentFilter filter = new IntentFilter();
        filter.addAction(STATUS_BAR_COVER_CLICK_ACTION);
        mContext.registerReceiver(onClickReceiver, filter);
        Intent buttonIntent = new Intent(STATUS_BAR_COVER_CLICK_ACTION);
        PendingIntent pendButtonIntent = PendingIntent.getBroadcast(mContext, 0, buttonIntent, 0);
        mRemoteViews.setOnClickPendingIntent(R.id.notify_cancel, pendButtonIntent);
        mRemoteViews.setTextViewText(R.id.name, mContext.getString(R.string.notification_downloading_info));
        mNotification = mBuilder.build();
        mNotification.flags = Notification.FLAG_ONGOING_EVENT;
        mNotificationManager.notify(NOTIFY_ID, mNotification);
    }

    /**
     * 下载Apk线程启动
     */
    private void downloadApk() {
        downLoadThread = new Thread(mdownApkRunnable);
        downLoadThread.start();
    }

    /**
     * 安装APk
     */
    protected void installApk() {
        File apkfile = new File(saveFileName);
        if (!apkfile.exists()) {
            return;
        }
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
        mContext.startActivity(i);
    }

    /**
     * 获取SD卡路径
     * @return
     */
    public String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();
        }
        return sdDir.toString();
    }
}